<?php
/**
 * Created by PhpStorm.
 * 阿里云推荐服务
 * User: caicm
 * Date: 2017/3/31
 * Time: 10:51
 */

namespace SDXApi\Service;


use SDXApi\Model\GoodsModel;
use SDXApi\Repositories\DiscoverGoodsRepository;
use SDXApi\Service\Kingdee\GoodsStockQueryService;

class RecommendService {

    /*
     * 热销 场景Code（首页）
     */
    protected $home = 'home';

    /*
     * 热销 场景Code（首页、详情）
     */
    protected $hot_sell = 'content_cf';

    /*
     * 热门 场景Code（首页、详情）
     */
    protected $hot = 'large_scale_';


    /*
     * 为你推荐 场景Code（首页、详情）
     */
    protected $recommend = 'detail_ofl';

    /*
     * 类似商品 场景Code（详情）
     */
    protected $similarity = 'itm_prop_rec';

    /*
     * 获取发现模块推荐商品
     * Created By caicm
     * @param int $user_id 用户id
     * @param int $group_num 获取组数
     * $num int $num 多少条一组
     * return mixed
     */
    public function get_goods_by_discover($user_id, $group_num, $num){
        $goods_list = array();
        $total = $group_num * $num ;
        $_POST['num'] = $total;
        $fatch = true;
        $k = 0;

        while ($fatch){
            $list = array();
            $plate = $k%4 + 1;
            //场景名称
            $code_name = $this->get_code_name($plate);
            //推荐列表
            $list = $this->get_list($code_name, $user_id, 0, $total, 8, 1, $plate);

            $goods_list = array_merge($goods_list, $list['goods_list']);
            if(count($goods_list) < $total){
                $k++;
                $fatch = true;
            }else{
                $fatch = false;
            }
        }

        shuffle($goods_list);
        $goods_list = array_slice($goods_list,0,$total);
        $goods_list = array_chunk($goods_list, $num);

        return $goods_list;

    }

    /**
     * @author Jerry
     * @param string $category_id
     * @param int $orientation
     * @param int $userId
     * @param int $wid
     * @return array|bool
     */
    public function getDiscoverGoodsHome($category_id = '', $orientation = 0, $userId = 0, $wid = 8)
    {
        $discover = new DiscoverGoodsRepository();
        $resultData = $discover->handleOrientationHome($orientation);

        $goodsModel = new GoodsModel();
        $goods = $goodsModel->getHomeDiscoverGoods($category_id, $resultData['number'], $userId, $wid);

        //处理金蝶商品库存
        $goodsStockQueryService = new GoodsStockQueryService();
        $goods = $goodsStockQueryService->getGoodsStockList($wid, $goods);

        $result = $discover->handleOrientationHomeGoods($goods, $resultData['albums_data']);
        return $result;
    }

    /*
     * 获取推荐列表
     * Created By caicm
     * @param string $code_name 场景名称
     * @param int $user_id 用户id
     * @param int $goods_id 商品id
     * @param int $num 获取条数（不传按分页全部输出）
     * @param int $wid 仓库id
     * @param int $page 分页
     * @param int $plate 板块位置
     * return mixed
     */
    public function get_list($code_name='home', $user_id=0, $goods_id=0, $num=0, $wid=8, $page=1, $plate=1){

        $id_list = $this->get_recommend_data($code_name, $user_id, $goods_id, $plate);

        if(!$id_list){
            return null;
        }

        if($goods_id){
            $limit = $num;
        }else{
            if($_POST['num']){
                //不分页
                $limit = $num;
            }else{
                //分页模式
                $page_size = 12;
                $goods_conut =D('Goods')->get_recomment_goods_count($id_list, $wid);

                $goods_conut = floor($goods_conut/3)*3;

                $goods_conut = $goods_conut > 150 ? 150 : $goods_conut;
                $pagecount = ceil($goods_conut/$page_size);
                $firstpage = ($page-1) * $page_size;
                $limit = $firstpage .','.$page_size;



                if($pagecount <= $page){

                    $page_size_rui = floor (($pagecount*$page_size-$goods_conut)/3)*3;
                    if($page_size_rui>0){
                        $limit = $firstpage .','.$page_size_rui; //最后一页区3的整数条数
                    }
//                    if($user_id == 2135){
//                        print_r($pagecount*$page_size-$goods_conut);
//                        print_r($limit);
//                    }


                    //判断是否为最后一页
                    $return_data['is_bottom'] = 1;
                }else{
                    $return_data['is_bottom'] = 0;
                }
                $return_data['total'] = $goods_conut;
                $return_data['page'] = array(
                    'firstpage' => $firstpage,
                    'pagecount' => $pagecount,
                    'pagesize' =>$page_size
                );
            }

        }

        $return_data['goods_list'] = D('Goods')->get_recomment_goods($code_name, $wid, $user_id, $id_list, $limit, $goods_id, $page, $_POST['num'], $plate);

        return $return_data;

    }

    /*
     * 获取推荐商品id
     * created By caicm
     * @param string $code_name 场景名称
     * @param int $user_id 用户id
     * @param int $goods_id 商品id
     * @param int $plate 板块位置
     * return string
     */
    protected function get_recommend_data($code_name, $user_id, $goods_id=0, $plate=1){

        //场景Code
        $code = $this->$code_name;

        if($goods_id){

            $data = $this->get_aliyun_data($code, $user_id, $goods_id);
            $id_list = $this->get_goods_id($data, $goods_id);

        }else{

            $key = "recommend_{$user_id}_{$plate}";
            $id_list = S($key);

            if(!$id_list){
                $data = $this->get_aliyun_data($code, $user_id, $goods_id);
                $id_list = $this->get_goods_id($data, $goods_id);

                //大于第4套模板，将对于的数据打乱
                if($plate > 4){
                    shuffle($id_list);
                }

                //写入缓存（30分钟）
                S($key, $id_list, 60*30);
            }
        }

        return implode(',', $id_list);

    }


    /*
     * 商品id处理
     * created By caicm
     */
    protected function get_goods_id($data, $goods_id){

        if(!$data['rec']){
            return '阿里云没有返回数据';
            //returnApiError('阿里云没有返回数据');
        }

        $id_list = array();
        foreach ($data['rec'] as $key=>$value){
            if($value['0'] != $goods_id ){
                $id_list[] = $value['0'];
            }
            if($goods_id && $key>=50){
                break;
            }
        }
        return $id_list;
    }

    /*
     * 获取阿里云推荐数据
     * created By caicm
     * @param $code 场景Code
     * @param $user_id 用户id
     * @param $goods_id 商品id
     * return mixed
     */
    protected function get_aliyun_data($code, $user_id, $goods_id=0){

        $url = $this->get_aliyun_url($code, $user_id, $goods_id);

        $data = get_recommend_shop($url);

        //当推荐引擎没有数据返回获取一个固定id的数据
        if(!$data['rec']){
            $url = $this->get_aliyun_url($code, 0, $goods_id);
            $data = get_recommend_shop($url);
        }

        return $data;

    }

    /*
     * 获取阿里云推url
     * created By caicm
     * @param $code 场景Code
     * @param $user_id 用户id
     * @param $goods_id 商品id
     * return string
     */
    protected function get_aliyun_url($code, $user_id, $goods_id=0){

        if($goods_id){
            return "https://shujuapi.aliyun.com/dataplus_129090/re/doRec?biz_code=sdx_code&scn_code={$code}&user_id={$user_id}&item_id={$goods_id}";
        }else{
            return "https://shujuapi.aliyun.com/dataplus_129090/re/doRec?biz_code=sdx_code&scn_code={$code}&user_id={$user_id}";
        }

    }

    /*
     * 获取场景名称
     * created By caicm
     * @param int $plate
     * return string
     */
    public function get_code_name($plate){
        switch ($plate){
            //首页
            case 1:
                $code_name = 'recommend';
                break;
            //购物车为空
            case 2:
                $code_name = 'home';
                break;
            //搜索结果为空
            case 3:
                $code_name = 'hot_sell';
                break;
            //常购清单为空
            case 4:
                $code_name = 'hot';
                break;
            //我的收藏为空
            case 5:
                $code_name = 'recommend';
                break;
            //我的订单为空
            case 6:
                $code_name = 'home';
                break;
            //足迹为空
            case 7:
                $code_name = 'hot_sell';
                break;
            //支付成功/支付失败
            case 8:
                $code_name = 'hot';
                break;
        }
        return $code_name;
    }

}